//
//  UUSupplierPeakSeasonEditVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 26/01/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUSupplierPeakSeasonEditVC.h"
#import "UUSupplierManager.h"
#import <UUFoundation/DKCalendarView.h>
#import <UUFoundation/DKCalendarDayConfiguration.h>

@interface UUSupplierPeakSeasonEditVC () <DKCalendarViewDelegate, UUSupplierManagerObserver>

@property (nonatomic, strong) DKCalendarView *calendarView;
@property (nonatomic, strong) UUSupplierPeakSeasonModel *peakSeason;

@property (nonatomic, strong) NSDictionary<NSString *, id> *peakSeasonDates;

@end

@implementation UUSupplierPeakSeasonEditVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.peakSeasonId) {
        self.peakSeason = [GetSupplierManager() fetchPeakSeasonModelWithId:self.peakSeasonId];
        self.title = self.peakSeason.name;
    } else {
        self.title = @"选择日期";
    }
    
    DKCalendarDayConfiguration *configuration = [DKCalendarDayConfiguration new];
    configuration.selectType = DKCalendarSelectTypeMultiple;
    
    configuration.minimumDate = [NSDate setupTimeWithThatDay:[NSDate date] format:@"000000"];
    NSDate *firstMonth = [NSDate dateWithTimeIntervalSince1970:[NSDate createYourNeedYear:[NSDate thisYearNumber] month:1 day:1]];
    configuration.maximumDate = [[firstMonth offsetMonth:12 * 3] offsetDay:-1];
    
    self.calendarView = [[DKCalendarView alloc] initWithConfiguration:configuration];
    self.calendarView.delegate = self;
    [self.view addSubview:self.calendarView];
    [self.calendarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_topLayoutGuideBottom);
        make.left.right.bottom.mas_equalTo(0);
    }];
    
    if (self.peakSeason) {
        [self.calendarView.configuration setSelectedDates:[self datesFromDatesString:self.peakSeason.dates]];
    }
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:@"保存" target:self selector:@selector(save)];
    
    [self updateOldPeakSeasons];
    [GetSupplierManager() addObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)updateOldPeakSeasons {
    NSArray<id> *peakSeasons = [GetSupplierManager() fetchPeakSeasons];
    
    NSMutableDictionary<NSString *, id> *peakSeasonDates = [NSMutableDictionary new];
    for (id peakSeasonId in peakSeasons) {
        if (![peakSeasonId isEqual:self.peakSeasonId]) {
            UUSupplierPeakSeasonModel *peakSeason = [GetSupplierManager() fetchPeakSeasonModelWithId:peakSeasonId];
            for (NSString *dateString in peakSeason.dates) {
                [peakSeasonDates setObject:peakSeasonId forKey:dateString];
            }
        }
    }
    
    self.peakSeasonDates = peakSeasonDates;
}

- (void)save {
    if (self.peakSeason == nil) { // 新建
        [UIAlertController presentAlertControllerWithTitle:@"请输入旺季名称" message:nil withTextFieldPlaceholder:@""
                                                 doneBlock:^(NSString *result) {
                                                     [self updatePeakSeasonWithPeakSeasonId:nil
                                                                                       name:result
                                                                                      dates:[self datesStringFromDates:[self.calendarView selectedDates]]];
                                                 } cancelBlock:nil];
    } else {
        [self updatePeakSeasonWithPeakSeasonId:self.peakSeasonId
                                          name:self.peakSeason.name
                                         dates:[self datesStringFromDates:[self.calendarView selectedDates]]];
    }
}

- (void)updatePeakSeasonWithPeakSeasonId:(NSNumber *)peakSeasonId name:(NSString *)name dates:(NSArray<NSString *> *)dates {
    WEAK_SELF();
    ShowIndicator();
    [GetSupplierManager() asyncUpdatePeakSeasonWithPeakSeasonId:peakSeasonId
                                                           name:name
                                                          dates:[self datesStringFromDates:[self.calendarView selectedDates]]
                                                  completeBlock:^(NSError * _Nullable error) {
                                                      HideIndicatorInView(weakSelf.view);
                                                      
                                                      if (error == nil) {
                                                          [weakSelf.navigationController popViewControllerAnimated:YES];
                                                      } else {
                                                          ShowTipsOnView(error.localizedDescription, weakSelf.view);
                                                      }
                                                  }];
}

- (NSArray<NSDate *> *)datesFromDatesString:(NSArray<NSString *> *)datesString {
    NSMutableArray<NSDate *> *dates = [NSMutableArray arrayWithCapacity:datesString.count];
    NSDate *today = [NSDate setupTimeWithThatDay:[NSDate date] format:@"000000"];
    for (NSString *dateString in datesString) {
        NSDate *date = [NSDate dateWithString:dateString format:@"yyyy-MM-dd"];
        if (![date isEarlierThanDate:today]) {
            [dates addObject:date];
        }
    }
    
    return dates;
}

- (NSArray<NSString *> *)datesStringFromDates:(NSArray<NSDate *> *)dates {
    NSMutableArray<NSString *> *datesString = [NSMutableArray arrayWithCapacity:dates.count];
    for (NSDate *date in dates) {
        NSString *dateString = [date formatDateByFormatString:@"yyyy-MM-dd"];
        [datesString addObject:dateString];
    }
    
    return datesString;
}

#pragma mark - UUSupplierManagerObserver methods

- (void)supplierManagerDidUpdatePeakSeasons {
    [self updateOldPeakSeasons];
}

#pragma mark - DKCalendarViewDelegate methods

- (BOOL)calendarView:(DKCalendarView *)calendarView willSelectDate:(NSDate *)date {
    NSString *dateString = [date formatDateByFormatString:@"yyyy-MM-dd"];
    id oldRule = self.peakSeasonDates[dateString];
    if (oldRule == nil) {
        return YES;
    } else {
        [UIAlertController presentAlertControllerWithTitle:[NSString stringWithFormat:@"该日期已被占用，如需继续使用请前往修改"]
                                                   message:nil
                                                 doneTitle:@"去修改"
                                               cancelTitle:@"取消"
                                             completeBlock:^(BOOL isCancelled) {
                                                 if (!isCancelled) {
                                                     UUSupplierPeakSeasonEditVC *editVC = [[self class] instanceOfAppropriate];
                                                     editVC.peakSeasonId = oldRule;
                                                     [self.navigationController pushViewController:editVC animated:YES];
                                                 }
                                             }];
        return NO;
    }
}

@end
